<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="700px" :defaultFullscreen="true">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./article.data"
  import { saveOrUpdateArticle } from "/@/api/sys/article"
  import { useMessage } from "/@/hooks/web/useMessage"

  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: "15%",
    schemas: formSchema,
    showActionButtonGroup: false,
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  })
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
      })
    }
  })

  const title = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))

  async function handleSubmit(v) {
    try {
      let values = await validate()
      setModalProps({ confirmLoading: true })
      await saveOrUpdateArticle(values, isUpdate.value)
      closeModal()
      emit("success")
      createMessage.success(`${title.value}成功`)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
